package xyz.jcat.generator.mybatis.config;

import xyz.jcat.generator.mybatis.convert.ITypeConvert;
import xyz.jcat.generator.mybatis.convert.MysqlTypeConvert;
import lombok.Getter;
import lombok.Setter;

/**
 * 数据库参数配置类
 *
 * @author yueyue
 * @Time 2017-05-15 16:50
 */
@Getter
@Setter
public class DbConfig {

    /**
     * 获取数据表信息类
     */
    private DBInfo dbInfo;
    /**
     * 数据表类型转换java类型的工具类
     */
    private ITypeConvert typeConvert;

    public void setDbName(String dbName) {
        this.dbInfo = DBInfo.init(dbName);
        if (DB.MYSQL.getName().equals(dbName)) {
            this.typeConvert = new MysqlTypeConvert();
        }
    }

    public void setDb(DB db) {
        setDbName(db.getName());
    }

    @Getter
    @Setter
    public static class DBInfo {
        /**
         * 数据库名称
         */
        private String dbName;
        /**
         * 该数据库查询所有表的sql语句
         */
        private String queryTablesSql;
        /**
         * 该数据库查询指定表名的表信息的sql语句
         */
        private String queryTableInfoSql;
        /**
         * 表信息的数据库字段名
         */
        private String fieldName;
        /**
         * 字段类型名
         */
        private String fieldTypeName;
        /**
         * 主键字段名
         */
        private String keyName;
        /**
         * 代表主键的字段值
         */
        private String pkName;
        /**
         * 注释名
         */
        private String comment;
        /**
         * 默认值字段名
         */
        private String defaultName;

        private DBInfo(String dbName, String queryTablesSql, String queryTableInfoSql,
                       String fieldName, String fieldTypeName, String keyName, String pkName, String comment, String defaultName) {
            this.dbName = dbName;
            this.queryTablesSql = queryTablesSql;
            this.queryTableInfoSql = queryTableInfoSql;
            this.fieldName = fieldName;
            this.fieldTypeName = fieldTypeName;
            this.keyName = keyName;
            this.pkName = pkName;
            this.comment = comment;
            this.defaultName = defaultName;
        }

        /**
         * 初始化获取表结构数据sql
         *
         * @param dbName
         * @return
         */
        public static DBInfo init(String dbName) {
            if (DB.MYSQL.getName().equals(dbName)) {
                return new DBInfo(DB.MYSQL.name(), "show tables", "show full fields from `%s`",
                        "FIELD", "TYPE", "KEY", "PRI", "COMMENT", "default");
            }
            return null;
        }
    }
}
